/* Copyright (c) 2016-2020 Enfry Ltd. All Rights Reserved.
 * 
 * This software is the confidential and proprietary information of Enfry. 
 * You shall not disclose such Confidential Information
 * and shall use it only in accordance with the terms of the agreements
 * you entered into with Enfry.
 */
package com.enfry.validation.validators;

import org.apache.commons.lang3.ClassUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.enfry.validation.IValidator;
import com.enfry.validation.config.Rule;
import com.enfry.validation.validators.BetweenValidator;

/**
 * 字符长度区间验证器
 * @Title com.enfry.validation.validators.BetweenValidator
 * @author liulei
 * @date 2016年7月22日
 */
public class BetweenValidator implements IValidator {
	private static final Logger logger = LoggerFactory
			.getLogger(BetweenValidator.class);

	@Override
	public boolean execute(Object data, Class<?> type, Object value, Rule rule) {
		if (value == null)
			return false;

		int length = 0;
		if (ClassUtils.isAssignable(type, Object[].class)) {
			length = ((Object[]) value).length;
		} else if (type == String.class) {
			length = ((String) value).trim().length();
		}
		String minString = rule.getParameter("min");
		int min = StringUtils.isNumeric(minString) ? Integer
				.parseInt(minString) : -1;
		String maxString = rule.getParameter("max");
		int max = StringUtils.isNumeric(maxString) ? Integer
				.parseInt(maxString) : -1;
		if (min == -1 || max == -1) {
			logger.warn("Invalid Parameter for minimun or maximun.");
			return false;
		}
		return length >= min && length <= max;
	}

}
